<?php if(!defined('ABSPATH')) die('not allowed');


class mymail_placeholder {
	
	private $content;
	private $placeholder = array();


	public function __construct($content = '', $basic = NULL) {
		$this->content = $content;
		
		//hardcoded tags
		if(!is_array($basic)){
			$timestamp = current_time('timestamp');
			$basic = array(
				'year' => date('Y', $timestamp),
				'month' => date('m', $timestamp),
				'day' => date('d', $timestamp),
				'hour' => date('H', $timestamp),
				'minute' => date('m', $timestamp),
			);
		}
		
		$this->add($basic);
		$this->add(mymail_option('custom_tags', array()));
		$this->add(mymail_option('tags', array()));
		$this->add($this->get_dynamic());

	}
	
	
	public function __destruct() {
	}
	
	public function set_content($content = '') {
		$this->content = $content;
	}
	public function get_content($removeunused = true, $placeholders = array() ) {
		return $this->do_placeholder($removeunused, $placeholders );
	}
	
	
	public function clear_placeholder( ) {
		$this->placeholder = array();
	}
	
	
	public function add( $placeholder = array() ) {
		if(empty($placeholder)) return false;
		foreach($placeholder as $key => $value){
			$this->placeholder[$key] = $value;
		}
	}
	
	public function do_placeholder($removeunused = true, $placeholders = array(), $round = 0 ) {
		
		$this->add($placeholders);
		
		foreach($this->placeholder as $search => $replace){
			$this->content = str_replace( '{' . $search . '}', $replace, $this->content );
		}
		
		if($count = preg_match_all( '#\{([a-z0-9-_]+)\|([^\}]+)\}#', $this->content, $hits_fallback )){
		
			for ( $i = 0; $i < $count; $i++ ) {
				
				$search = $hits_fallback[0][$i];
				$placeholder = $hits_fallback[1][$i];
				$fallback = $hits_fallback[2][$i];
				//use placeholder
		
				if ( !empty( $this->placeholder[$placeholder] ) ) {
					$this->content = str_replace( $search, $this->placeholder[$placeholder], $this->content );
				
				//use fallback
				} else if($removeunused && $round){
				
					$this->content = str_replace( $search, $fallback, $this->content );
					
				}
			}
			
		}
		
		//do it twice to get tags inside tags ;)
		if(!$round)	return $this->do_placeholder($removeunused, $placeholders, 1 );
		
		
		//remove unused placeholders
		if($removeunused){
			$this->content = preg_replace('#\{([a-z0-9-_:|]+)\}#','', $this->content);
		}
		
		return $this->content;
		
	}
	
	public function replace_links($base, $links = array(), $hash = '') {
		$used = array();
		foreach ( $links as $link ) {
			
			$search = '"'.$link.'"';
			
			if(!isset($used[$link])){
				$replace = '"'.$base . '&k=' . $hash . '&t=' . urlencode( $link ).'&c=0"';
				$used[$link] = 1;
			}else{
				$replace = '"'.$base . '&k=' . $hash . '&t=' . urlencode( $link ).'&c='.($used[$link]++).'"';
			}
			
			$pos = strpos($this->content, $search);
			if ($pos !== false) {
				$this->content = substr_replace( $this->content, $replace, $pos, strlen($search) );
			}			
		}
	}
	
	
	public function share_service($url, $title = '' ) {
		
		$placeholders = array();
		
		if($count = preg_match_all('#\{(share:(twitter|facebook|google|linkedin) ?([^}]+)?)\}#', $this->content, $hits)){
			
			require_once MYMAIL_DIR.'/includes/social_services.php';
			
			for($i = 0; $i < $count; $i++){

				$service = $hits[2][$i];
				
				if(isset($mymail_social_services[$service]))
				
					$_url = str_replace('%title', (!empty($hits[3][$i])) ? '' : urlencode($title), ($mymail_social_services[$service]['url']));
					$_url = str_replace('%url', (!empty($hits[3][$i])) ? urlencode($hits[3][$i]) : urlencode(($url)), $_url);
					
					$url_content = apply_filters('mymail_share_button_'.$service, '<img src="'.MYMAIL_URI.'/assets/img/share/share_'.$service.'.png" />');
					$placeholders[$hits[1][$i]] = '<a href="'.$_url.'" class="social">'.$url_content.'</a>'."\n";
					
				
			}
			
		}
		
		$this->add($placeholders);
		
	}
	
	
	public function get_dynamic( ) {
		
		$placeholders = array();
		
		if($count = preg_match_all('#\{(post_([^}-]+):([\d]+))\}#', $this->content, $hits)){
			
			for($i = 0; $i < $count; $i++){
				$post = get_post($hits[3][$i]);
				if($post){
					$what = $hits[2][$i];
					switch($what){
						case 'link':
						case 'permalink':
							$replace_to = get_permalink($post->ID);
							break;
						case 'date':
						case 'date_gmt':
						case 'modified':
						case 'modified_gmt':
							$replace_to = date(get_option('date_format').' '.get_option('time_format'), strtotime($post->{'post_'.$what}));
							break;
						default:
							$replace_to = isset($post->{'post_'.$what})
								? $post->{'post_'.$what}
								: $post->{$what};
					}
					
					$placeholders[$hits[1][$i]] = $replace_to;
				}
			}
			
		}
		
		if($count = preg_match_all('#\{(post_([^}-]+):-([\d]+))\}#', $this->content, $hits)){
			
			for($i = 0; $i < $count; $i++){
			
				$post = $this->get_last_post( $hits[3][$i]-1 );
				
				if($post){
					$what = $hits[2][$i];
					switch($what){
						case 'link':
						case 'permalink':
							$replace_to = get_permalink($post->ID);
							break;
						case 'date':
						case 'date_gmt':
						case 'modified':
						case 'modified_gmt':
							$replace_to = date(get_option('date_format').' '.get_option('time_format'), strtotime($post->{'post_'.$what}));
							break;
						default:
							$replace_to = isset($post->{'post_'.$what})
								? $post->{'post_'.$what}
								: $post->{$what};
					}
					
					$placeholders[$hits[1][$i]] = $replace_to;
				}
			}
			
		}
		
		if($count = preg_match_all('#\{(post_([^}-]+):last)\}#', $this->content, $hits)){
		
			if($post = $this->get_last_post( )){
			
				for($i = 0; $i < $count; $i++){
					$placeholders[$hits[1][$i]] = isset($post->{'post_'.$hits[2][$i]})
						? $post->{'post_'.$hits[2][$i]}
						: $post->{$hits[2][$i]};
						
				}
				
			}
			
		}
		
		if($count = preg_match_all('#\{(tweet:([^}|]+)\|?([^}]+)?)\}#', $this->content, $hits)){
			
			for($i = 0; $i < $count; $i++){
				$tweet = $this->get_last_tweet($hits[2][$i]);
				$placeholders[$hits[1][$i]] = (!empty($tweet)) ? $tweet : $hits[3][$i];
			}
			
		}
		
		return $placeholders;
	}
	
	
	private function get_last_post( $offset = 0 ) {
		$post = get_posts( array(
			'numberposts' => 1,
			'offset' => $offset,
		));
		
		return ($post) ? $post[0] : false;
	}
	
	private function get_last_tweet( $username ) {
		
		if ( false === ( $tweet = get_transient( 'mymail_tweet_'.$username ) ) ) {
			$response = wp_remote_get('http://api.twitter.com/1/statuses/user_timeline/'.$username.'.json?exclude_replies=1&include_rts=1&count=1&include_entities=1');
			$data = json_decode($response['body']);
			
			if(isset($data->errors)) return '';
			
			$tweet = $data[0];
			
			if(!isset($tweet->text)) return '';
			
			if($tweet->entities->hashtags){
				foreach($tweet->entities->hashtags as $hashtag) {
					$tweet->text = str_replace('#'.$hashtag->text, '#<a href="https://twitter.com/search/%23'.$hashtag->text.'">'.$hashtag->text.'</a>', $tweet->text);
					
				}
			}
			if($tweet->entities->urls){
				foreach($tweet->entities->urls as $url) {
					$tweet->text = str_replace($url->url, '<a href="'.$url->url.'">'.$url->display_url.'</a>', $tweet->text);
					
				}
			}
			
			//$tweet->text = preg_replace('/(http|https|ftp|ftps)\:\/\/([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*))?/','<a href="\0">\2</a>', $tweet->text);
			//$tweet->text = preg_replace('/(^|\s)#(\w+)/','\1#<a href="https://twitter.com/search/%23\2">\2</a>',$tweet->text);
			$tweet->text = preg_replace('/(^|\s)@(\w+)/','\1@<a href="https://twitter.com/\2">\2</a>', $tweet->text);
			
			set_transient( 'mymail_tweet_'.$username , $tweet, 60*mymail_option('tweet_cache_time') );
		}
		
		return $tweet->text;
	}
	


}
?>